import socket
import e32db
import appuifw

def set_accesspoint():
  apid = socket.select_access_point()
  apo = socket.access_point(apid)
  socket.set_default_access_point(apo)
  
class UserDB:
  def __init__(self, dbfile):
    self.id = ''    
    try:
      self.db = e32db.Dbms()
      self.db.open(dbfile)
    except:
      self.db.create(dbfile)
      self.db.open(dbfile)
      self.db.execute(u"CREATE TABLE users (id VARCHAR, pwd VARCHAR)")

  def read(self):
    dbv = e32db.Db_view()
    dbv.prepare(self.db, u"SELECT id, pwd from users")
    dbv.first_line()
    try: 
      dbv.get_line()
      self.id = dbv.col(1)
      self.pwd = dbv.col(2)
    except:
      self.id = ''
      self.pwd = ''

  def write(self, id, pwd):
    if self.id == '':
      sql = "INSERT INTO users (id, pwd) VALUES ('%s', '%s')" % (id, pwd)
    else:
      sql = "UPDATE users set id='%s', pwd='%s'" % (id, pwd) 
    self.db.execute(unicode(sql))
    self.id = id
    self.pwd = pwd

  def clear(self):
    self.db.execute(unicode("DELETE FROM users"))

  def close(self):
    self.db.close()
    
def user_auth(dbfile="c:\\gdata.db"):    
  db = UserDB(unicode(dbfile))
  db.read()
  nid = appuifw.query(u"Account:", "text", db.id)
  npwd = appuifw.query(u"Password:", "text", db.pwd)
  if nid != db.id or npwd != db.pwd:
    db.write(nid, npwd) 
  db.close()
  return (nid, npwd)
  
  